/**
 * @Author: easten
 * @Created: 2024-04-15 23:48:14
 * @Description:
 *
 */
import { DrawerProps, TreeDataModel } from "_common/DataType";
import { AxiosInstance } from "axios";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { Drawer } from "tdesign-react";
import { ApiAlarm } from "_common/api/iot";
import { IotAlarm } from "_common/entity";
import { DeviceRecordTypes, ProductCode } from "_common/enum";
import ReactEcharts from "echarts-for-react";
type AlarmDrawerProps = DrawerProps & {
  axios: AxiosInstance;
  startTime?: string;
  endTime?: string;
  device?: TreeDataModel;
  treeType: "station" | "device";
};
const AlarmDrawer: React.FC<AlarmDrawerProps> = (props: AlarmDrawerProps) => {
  const { open, onSuccess, axios, device, startTime, endTime, treeType } =
    props;

  const [dataSource, setDataSource] = useState<IotAlarm[]>([]);
  const apiAlarm = new ApiAlarm(axios);
  const chartRef = useRef<any>(null);
  const [chartNode, setChartNode] = useState<JSX.Element | null>(null);
  useEffect(() => {
    getAlarm();
  }, [device, startTime, endTime, open, treeType]);

  const getAlarm = async () => {
    const response = await apiAlarm.getList({
      deviceCode: treeType == "station" ? device?.deviceCode : device?.value,
      startTime: startTime,
      endTime: endTime,
    });
    if (response && response.code == 200 && response.data) {
      setDataSource(response.data);
    }
  };

  const handleClose = () => {
    onSuccess?.(false);
  };
  /*  {
    name: "温度",
    type: "line",
    smooth: true,
    symbolSize: 1,
    data: value?.map((a) => a.value1),
  }, */
  const option = useMemo(() => {
    let legend: string[] = [];
    let xData: string[] = [];
    let yData: any[] = [];

    if (dataSource) {
      let fieldObj =
        treeType == "station"
          ? DeviceRecordTypes[109]
          : device?.data?.dtCode != null
            ? DeviceRecordTypes[device?.data?.dtCode as ProductCode]
            : { bane: "" };
      let fields = Object.values(fieldObj);
      legend = fields.map((a) => a.name);
      xData = dataSource?.map((a) => a.time) as [];
      yData = fields.map((a) => {
        return {
          name: a.name,
          type: "line",
          smooth: true,
          symbolSize: 1,
          data: dataSource?.map((b) => (b as any)[a.field]),
        };
      });
    }
    return {
      backgroundColor: "transparent", //背景颜色
      tooltip: {
        trigger: "axis",
        borderWidth: 1, //提示框边框的大小
        borderColor: "#333", //提示框边框的颜色
        backgroundColor: "#063046", //提示框的背景颜色（0.9为透明度）
        textStyle: {
          fontSize: 12, //提示框的字体大小
          color: "#01D3C5", //提示框里的字体颜色
          aligin: "center",
        },
      },
      color: ["#23B052", "#12C3C3", "#2C8EE8", "#FFAE32", "#0A8260"], //颜色配置
      legend: {
        data: legend,
        right: 30, // 距离右侧的距离
        top: 5, // 距离顶部的距离
        textStyle: {
          // color: [ '#','#'], // 标签头 提示文字的颜色
          fontSize: 12,
          color: "#D0D3D7",
        },
        icon: "icon", //icon 长方形 circle 圆形 arrow箭头型 diamond菱形
        // triangle三角形  emptyDiamond 空心菱形
        //emptyCircle 空心圆型 emptyRectangle 空心长方形 emptyTriangle 空心三角形
      },
      dataZoom: [
        {
          type: "slider",
          realtime: true,
          //拖拉
          handleSize: "100%", //滑动条两侧的大小
          start: 0, //开始位置
          end: 50, //结束位置
          bottom: 10, //居下的距离
          textStyle: {
            color: "#1bb4f6", // 滑动条的文字颜色
          },
          height: 20,
        },
      ],
      grid: {
        left: "3%", //整个曲线居左的距离
        right: "4%", //整个曲线居右左的距离
        bottom: "10%", //整个曲线居下左的距离
        height: "80%", //整个曲线的高
        containLabel: true,
      },
      toolbox: {
        show: true,
        feature: {
          // dataZoom: {},
          // dataView: {
          //   readOnly: true,
          // },
          // magicType: {
          //   type: ['line', 'bar', 'pie'],
          // },
          restore: {},
          // textStyle: {
          //   color: '#1bb4f6', // 左上角切换的颜色
          // },
          // saveAsImage: {}
        },
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: xData,

        axisLine: {
          lineStyle: {
            color: "#0E556C", //设置X轴的颜色
            width: 1, //设置X轴的粗细
          },
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: "#117CB1", //Y轴的数据字体颜色
          },
        },
      },
      yAxis: [
        {
          name: "值", //左侧单位
          nameTextStyle: {
            color: "#178AC3", //左侧单位文字
          },
          type: "value",
          axisLine: {
            lineStyle: {
              color: "red", //设置Y轴的颜色
              width: 1, //设置Y轴的粗细
            },
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: "#117CB1", //Y轴的数据字体颜色
            },
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: "#0E556C", //网格线的颜色
            },
          },
        },
      ],
      series: yData,
    };
  }, [dataSource, device, open, chartRef, treeType]);

  useEffect(() => {
    if (chartRef.current && option && open) {
      setChartNode(<ReactEcharts option={option} style={{ height: 400 }} />);
    }
  }, [chartRef.current, option, open]);

  return (
    <Drawer
      header={`${device?.label}-历史报警数据曲线`}
      footer={false}
      visible={open}
      showOverlay={false}
      size="medium"
      placement="bottom"
      onClose={handleClose}
    >
      <div ref={chartRef}>{chartNode}</div>
    </Drawer>
  );
};
export default AlarmDrawer;
